﻿;(function($, window, undefined) {
	var zIndex = 1024, _count = 1;
	var _expando = (new Date).getTime() - 0;
	var $window = $(window);
	var $document = $(document);
	var pop = function(options) {
		typeof options == 'string' && (options = {content: options});
		options = $.extend(!0, {}, pop.defaults, options);
		var id = options.id = options.id || 'u' + _count, api = pop.get(id);
		if (api) return api.focus();
		return pop.list[id] = new pop.fn.create(options);
	};
    pop.fn = pop.prototype = {
		destroyed: true,
		_timer: false,
		open: false,
	    create: function(options) {
		    var that = this;
		    this.id = options.id;
			this.sid = 'sid-' + this.id,
			this.options = options;
		    this.destroyed = false;
			this.zIndex = Math.max(zIndex, this.options.zIndex);
			++_count;
			++zIndex;

            // 创建 wrapper 属性
            this._wrapper = $('<div/>', {
                id: this.id,
                'class': this.options.theme + '-wrapper'
            }).css({
				position: this.options.fixed ? 'fixed' : 'absolute',
                display: 'none'
            }).appendTo(this.options.appendTo);

            // 创建属性
            this._loading =  $('<div class="' + this.options.theme + '-loading"/>');
            this._body =     $('<div class="' + this.options.theme + '-body"/>').appendTo(this._wrapper);
            this._header =   $('<div class="' + this.options.theme + '-header"/>').hide().appendTo(this._body);
            this._title =    $('<div class="' + this.options.theme + '-title"/>').hide().appendTo(this._header);
            this._content =  $('<div class="' + this.options.theme + '-content"/>').appendTo(this._body);
            this._footer =   $('<div class="' + this.options.theme + '-footer"/>').hide().appendTo(this._body);
            this._button =   $('<div class="' + this.options.theme + '-button"/>').hide().appendTo(this._footer);
            this._mask =     $('<div class="' + this.options.theme + '-mask"/>').hide().insertBefore(this._wrapper);
			
			this._content.html(this.options.content || this._loading);

			!this.eventExist('show') && this.setEvent('show', function(modal) {

			    this._wrapper.show();
			
			    modal && this._mask.show().css({
					position: 'fixed',
					left: 0,
					top: 0,
					width: '100%',
					height: '100%',
					overflow: 'hidden',
					userSelect: 'none',
				    opacity: this.options.maskOpacity,
				    background: this.options.maskBackground,
			    }).animate({
				    opacity: 0.7
			    }, 150);
			});

			!this.eventExist('close') && this.setEvent('close', function() {
				this._wrapper.hide();
				this._mask.hide();
			});

			!this.eventExist('remove') && this.setEvent('remove', function() {
				this._wrapper.remove();
				this._mask.remove();
				this.destroy();
			});

			!this.eventExist('ok') && this.setEvent('ok', function() {
				this.close().remove(); 
				return false;
			});

			!this.eventExist('cancel') && this.setEvent('cancel', function() {
				this.close().remove(); 
				return false;
			});
			
			!this.eventExist('position') && this.setEvent('position', function() {
			    var dl = this.options.fixed ? 0 : $document.scrollLeft();
			    var dt = this.options.fixed ? 0 : $document.scrollTop();
			    var ww = $window.width();
			    var wh = $window.height();
			    var ow = this._wrapper.width();
			    var oh = this._wrapper.height();
			    var left = (ww - ow) / 2 + dl;
			    var top = (wh - oh) * 382 / 1000 + dt;
			    var style = this._wrapper[0].style;
			    style.left = Math.max(parseInt(left), dl) + 'px';
			    style.top = Math.max(parseInt(top), dt) + 'px'
			});
			
			this.options.resize && $window.on('resize.' + this.sid, function() {
				this.__timeout && clearTimeout(this.__timeout);
				this.__timeout = setTimeout(function(){that.position();}, 15);
			});

			$.each(this.options.buttons, function(e, b) {
				that.button(b, e);
			});

			this.trigger('init');

		    return this;
	    },
	    time: function (time) {
			if (!this.destroyed && this.open) {
		        var that = this;
		        if (time) {
		            this._timer && clearTimeout(this._timer);
			        this._timer = setTimeout(function(){
				        that.close().remove();
			        }, time);
		        };
			}
		    return this;
	    },
		show: function(modal) {
			if (!this.destroyed) {
				this.open = true;
			    this.trigger('show', !1, modal);
				this.position().focus();
			}
			return this;
		},
		close: function() {
			if (!this.destroyed && this.open) {
				this.open = false;
			    this.trigger('close');
			}
			return this;
		},
		remove: function() {
			if(!this.destroyed) {
			    this.trigger('remove');
			}
			return this;
		},
		destroy: function() {
			if(!this.destroyed) {
				$window.off('.' + this.sid);
				delete pop.list[this.id];
			    for (var i in this) {
				    delete this[i]
			    }
			}
		},
		body: function(html, is) {
			this._body[is ? 'append' : 'html'](html);
			return this;
		},
		header: function(html, is) {
			this._header[is ? 'append' : 'html'](html);
			return this;
		},
		footer: function(html, is) {
			this._footer[is ? 'append' : 'html'](html);
			return this;
		},		
		content: function(html, is) {
			this._content[is ? 'append' : 'html'](html);
			this.position().focus();
			return this;
		},
		title: function(html, is) {
			this._title[html ? 'show' : 'hide']()[is ? 'append' : 'html'](html);
			this._header[html ? 'show' : 'hide']();
			return this;
		},
		width: function(value) {
			this._body.css('width', value);
			return this;
		},
		height: function(value) {
			this._body.css('height', value);
			return this;
		},
		loading: function() {
			this._content.html(this._loading);
			return this;
		},
		position: function() {
			this.trigger('position');
			return this;
		},
		focus: function() {
			this._mask.css('zIndex', this.zIndex);
			this.zIndex++;
			this._wrapper.css('zIndex', this.zIndex);
			return this;
		},
		button: function(b, e) {
			var that = this;
			this._button[b ? 'show' : 'hide']().append(b);
			this._footer[b ? 'show' : 'hide']();
			b.on('click.' + this.sid, function() {
				that.trigger(e) !== false && that.close().remove();
			});
			return this;
		},
		eventExist: function(name) {
			return typeof this.options.events[name] == "function";
		},
		getEvent: function(name) {
			return this.options.events[name];
		},
		setEvent: function(name, func) {
			this.options.events[name] = func;
		},
		removeEvent: function(name) {
			this.options.events[name] && delete this.options.events[name];
		},
		cleanEvent: function() {
			for (var a in this.options.events) delete this.options.events[a];
		},
		trigger: function(e, n) {
			if (!this.destroyed || n) {
				return this.eventExist(e) ? this.options.events[e].apply(this, Array.prototype.slice.call(arguments, 2)) : void 0;
			}
		}
	};

    pop.fn.create.prototype = pop.fn;
	
    // 快捷方式绑定触发元素
    $.fn.pop = function () {
        var config = arguments;
        this.on('click', function () {
            pop.apply(this, config).show();
            return false;
        });
        return this;
    };
	
	pop.get = function(id) {
		return id === undefined ? pop.list : pop.list[id];
	};
	pop.list = {};
	pop.defaults = {
		zIndex: 0,
		resize: !0,
		theme: 'ui-dialog',
		events:{},
		id: null, 
		appendTo: $('body'),
		content: '',
		buttons: {
			//cancel: $('<button class="ui-cancel" type="button">取消</button>'),
			//ok:  $('<button class="ui-ok" type="button">确定</button>'),
		},
		maskBackground: '#000',
		maskOpacity: 0.7,
	};
	this.pop = pop;
}(this.jQuery, this));

(function($, undefined) {
	"use strict";
	$.ajaxPrefilter(function(options, origOptions, jqXHR) {
		if (options.iframe) {
			options.originalURL = options.url;
			return "iframe"
		}
	});
	$.ajaxTransport("iframe", function(options, origOptions, jqXHR) {
		var form = null,
			iframe = null,
			name = "iframe-" + $.now(),
			input = $(options.files);
		options.dataTypes.shift();
		options.data = origOptions.data;
		if (input.length) {
			form = $("<form enctype='multipart/form-data' method='post'></form>").hide().attr({
				action: options.originalURL,
				target: name
			});
			
			if (typeof(options.data) === "string" && options.data.length > 0) {
				$.error("data must not be serialized")
			}

            if (options.data) {
                $.each(options.data, function (key, value) {
                    $('<input type="hidden"/>').prop('name', key).val(value).appendTo(form);
                });
            }

			return {
				send: function(headers, completeCallback) {
					iframe = $("<iframe src='about:blank' name='" + name + "' id='" + name + "' style='display:none'></iframe>");
	                input.before(input.clone().val(''));
	                input.appendTo(form);
	                iframe.appendTo("body");
	                form.appendTo("body");
                    form.on('submit', function(e) {

                        //加载事件
                        iframe.on("load", function (e) {
                            var body = $(this).contents().find('body');
		                    completeCallback(200, "OK", {
                                html: body.html(),
				                text: body.text()}
                            );
		
                            setTimeout(function(){
		                        form.off("submit").remove();
		                        iframe.off("load").remove();				
		                    }, 100)
                        });	
                    }).submit();
			    },
			    abort: function() {
					if (iframe !== null) {
		                form.off("submit").remove();
		                iframe.off("load").remove();
					}
				}
			}
		}
	})
})(jQuery);

$.alert = function(content, closeFn, time) {
	time = time > -1 ? time : 1500;
	var d, html = '<div class="bold">' + content + '</div>';
	if(d = pop.get('alert')) return d.content(html).time(time);
	d = pop({
		id: 'alert',
		fixed: !0,
		content: html,
		closeFn: closeFn
	}).show().time(time);
	return d;
};

$.fn.tips = function(content, time) {
	time = time > -1 ? time : 1500;
	return this.each(function() {
	    var jthis = $(this), $parent = jthis.parent();
	    jthis.queue(function(next) {
	        pop({
				resize: !1,
				appendTo: $parent,
				id:'#_tips',
		        closeFn: !1,
		        events:{ 
		            position: function() {
                        $parent.css('position') != 'relative' && $parent.css('position', 'relative');
				        this._wrapper.css({
				            top: $parent.outerHeight() + 6,
				            left: 0
			            })
					}
		        },

		        content: '<div class="bold">' + content + '</div>'
	        }).show().time(time);
		    next();
	    });
	});
};

$.confirm = function(content, openFn, closeFn) {
	var d = pop({
		maskBackground: '#ddd',
		maskOpacity: 0.3,
		id: 'confirm',
		content: '<div class="bold">' + content + '</div>',
		fixed: !0,
		events:{ 
		    ok: openFn,
		    cancel: closeFn || function() {return !0;}
		},
		buttons: {
			cancel: $('<button class="ui-cancel" type="button">取消</button>'),
			ok:  $('<button class="ui-ok" type="button">确定</button>'),
		}
	}).show(1);
	return d;
};

// 支持连续操作 $submit.button(message).delay(1000).button('reset').delay(1000).location('http://xxxx');
$.fn.location = function(href) {
	return this.each(function() {
	    var jthis = $(this);
	    jthis.queue(function(next) {
		    if(href) {
			    window.location = href;
		    } else if(href == 0) {
			    window.location.reload();
		    }
		    next();
	    });
    });
}

// 支持连续操作 jsubmit.button(message).delay(1000).button('reset');
$.fn.button = function(status) {
	return this.each(function() {
		var jthis = $(this);
		jthis.queue(function (next) {
			var loading_text = jthis.attr('loading-text') || jthis.data('loading-text');
			if(status == 'loading') {
				jthis.prop('disabled', true).addClass('disabled').attr('default-text', jthis.text());
				jthis.html(loading_text);
			} else if(status == 'disabled') {
				jthis.prop('disabled', true).addClass('disabled');
			} else if(status == 'enable') {
				jthis.prop('disabled', false).removeClass('disabled');
			} else if(status == 'reset') {
				jthis.prop('disabled', false).removeClass('disabled');
				if(jthis.attr('default-text')) {
					jthis.text(jthis.attr('default-text'));
				}
			} else {
				jthis.text(status);
			}
			next();
		});
	});
};

$.fn.selectAll = function(elem, list, row, checked) {
	checked = checked || 'checked';
    var $list = $(list);
	return this.each(function() {
        $(this).on('click', elem, function() {
			//$(this).toggleClass("selected");
	        var s = $list.data("selectall");
            if (true == s) {
				$list.find(row).removeClass(checked);
				$list.data("selectall", false);
            } else {
				$list.find(row).addClass(checked);
				$list.data("selectall", true);
            }
        });
	});
};

$.fn.selectRow = function(row, checked) {
	checked = checked || 'checked';
	return this.each(function() {
        $(this).on('click', row, function(e) {
            var target = $(e.toElement ? e.toElement : e.target),
			tagName = target.prop('tagName').toLowerCase();
            if ($.inArray(tagName, ['input', 'textarea', 'a', 'button', 'i']) >= 0) {
                e.stopPropagation();
            } else {
                var t = $(this);
                if (t.hasClass(checked)) {
                    t.removeClass(checked);
                } else {
                    t.addClass(checked);
                }
			}
        });
	});
};

$.fn.checked = function(row, item, checked) {
	checked = checked || '.checked';
    var r = [];
	$(this).find(row).filter(checked).each(function(){
		r.push($(this).data(item));
	});
    return r;
};

$.fn.deleteRow = function(elem, list, row, selectClass) {	
    var $list = $(list);	
	return this.each(function() {
		$(this).on('click', elem, function() {
		    var $elem   = $(this), 
			confirmtext = $elem.data('confirm'), 
			url         = $elem.data('action'), 
			item        = $elem.data('item');
            var func = function(){
			    var post = {};
				post[item] = $list.checked(row, item, selectClass);
				if(!url || !post) return ;
	            var d = pop({
					events:{
                        show:function(modal) {

			                this._wrapper.show();
			
			                modal && this._mask.show().css({
					            position: 'fixed',
					            left: 0,
					            top: 0,
					            width: '100%',
					            height: '100%',
					            overflow: 'hidden',
					            userSelect: 'none',
				                opacity: 0
			                });
			            }
					},
					buttons:''
				}).show(1);
				$.xpost(url, post, function(code, message, data) {
					if(code == 0){
			            $.alert(message);
					    $.each(data, function(k, v) {
						    $list.find('[data-' + item + '='+v+']').remove();
					    });
					    !$list.find(row).length && setTimeout(function(){
				            window.location.reload();
			            }, 1500);
					} else if(data) {
			            typeof data.location !== null && (window.location = data.location);
					}
					d.close().remove();
		        });
	        };
	        confirmtext ? $.confirm(confirmtext, func) : func();
        });
	});
};

//提交表单
$.fn.ajaxSubmit = function(submit) {
	return this.each(function() {
	    var $form = $(this),$submit = $(submit || $form.find('[type="submit"]'));
	    $form.on('submit', function() {
		    $submit.button('loading');
			$.xpost($form.attr("action"), $form.serialize(), function(code, message, data) {
		        if(code < 1) {
			        code < 0 && $.alert(message, null, 0);
			        data && typeof data.location !== null ? $submit.text(message).delay(1000).location(data.location) : $submit.text(message).delay(1000).button('reset');
		        } else {
			        $form.find('[name="'+code+'"]').tips(message).focus();
			        $submit.button('reset');
		        }
		    });
		    return false;
	    });
	});
};

//ajaxClick
$.fn.ajaxClick = function(elem) {
	return this.each(function() {
		var $list = $(this);
	    $list.on('click', elem, function() {
			if($.once) return false;
			var $elem = $(this), confirmtext = $elem.data('confirm');
			var func  = function(){
				$.once = !0;
				$elem.button('loading');
				$.xpost($elem.prop('href') || $elem.data('href'), $elem.data(), function(code, message, data) {
			        code != 0 && $.alert(message);
					data && typeof data.location !== null ? $elem.text(message).delay(1000).location(data.location) : $elem.text(message).delay(1000).button('reset');
					$.once = !1;
		        });
			};
			
			confirmtext ? $.confirm(confirmtext, func) : func();
			
		    return false;
	    });
	});
};


$.xpost = function(url, postdata, callback) {
	if($.isFunction(postdata)) {
		callback = postdata;
		postdata = null;
	}
	
	$.ajax({
		type: 'POST',
		url: url,
		data: postdata,
		dataType: 'text',
		timeout: 6000000,
		success: function(r){
			
			if(!r) return callback(-1, 'Server Response Empty!');
	        try {
		        // 去掉广告代码。
		        // r = r.replace(/\}\s*<script[^>]*>[\s\S]*?<\/script>\s*$/ig, '}');
		        if(r.match(/^<!DOCTYPE/i)) return null;
		        r = $.parseJSON(r);
		        return callback(r.code, r.msg, r.data);
	        } catch(e) {
		        //window.json_error_string = s;	// 记录到全局
		        return callback(-1, 'Server Response Not JSON：'+r);
	        }
		},
		error: function(xhr, type) {
			if(type != 'abort' && type != 'error' || xhr.status == 403) {
				return callback(-1000, "xhr.responseText:"+xhr.responseText+', type:'+type);
			} else {
				return callback(-1001, "xhr.responseText:"+xhr.responseText+', type:'+type);
				console.log("xhr.responseText:"+xhr.responseText+', type:'+type);
			}
		}
	});
};
